package gotnames.email;

import gotnames.Utils;
import gotnames.dm.User;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.io.IOUtils;

import com.medallia.tiny.string.StringTemplateBuilder;

/**
 * Class which handles sending emails to user inviting them to use Got Names.
 */
public class InviteEmail {
	private static final Logger LOG = Utils.getLog();
	
	/** The URL to put in the invite email */
	public static final String WEB_URL = "http://got-names.appspot.com";
	
	/**
	 * Send an email invite to the given user.
	 * 
	 * @param firstInvite true if this is the first invite being send to the user
	 */
	public static void sendTo(User user, boolean firstInvite) throws IOException, MessagingException {
		String email = user.getEmail();
		
		String msgBody = StringTemplateBuilder.t()
			.attr("url", WEB_URL)
			.attr("firstInvite", firstInvite)
			.attr("profilePicture", user.isProfilePicture())
			.attr("token", user.getAuthToken())
			.go(IOUtils.toString(InviteEmail.class.getResourceAsStream("inviteEmail.st"))).toString();
		
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress("noreply@got-names.appspotmail.com", "Got Names?"));
		msg.addRecipient(RecipientType.TO, new InternetAddress(email));
		msg.setSubject("Welcome to Got Names?");
		msg.setText(msgBody);

		Transport.send(msg);
		
		LOG.info("Sent InviteEmail to " + email + ", firstInvite: " + firstInvite);
		System.out.println(msgBody);
	}

}
